<!--
 * @Author: captern
 * @@Gitee: https://gitee.com/captern
 * @@websit: http://www.captern.cn/
 * @Date: 2021-02-05 15:14:26
 * @LastModifiedBy: captern
 * @LastEditTime: 2021-04-13 14:51:38
 * @Description:
-->
<template>
	<view class="content">
		<image class="bg-img" src="../../static/game/img-renwu-bg@2x.png" mode="scaleToFill"></image>
		<view class="top-view">
			<image class="top-box-bg" src="../../static/receive/img-renwu-150-peitu@2x.png" mode="scaleToFill"></image>
			<view class="box topBox">
				<view class="box-content">
					<text>小朋友，请把积木墙补充完整，解锁关卡，即可获得钥匙碎片一枚。</text>
				</view>
			</view>
			<image class="show-icon" :src="guideRole[nowGuideId-1]" mode="aspectFit"></image>
			<view class="box-border">
				<view class="top-box-view">
					<image src="../../static/game/icon-48-yaoshi@2x.png" mode="aspectFit"></image>
					<text>{{gameInfo.key_num}}</text>
				</view>
			</view>
		</view>
		<view class="movableArea">
			<view class="box midden-view" >
				<view class="image-view">
					<image class="img-bg" :src="bgSrc" mode="scaleToFill"></image>
					<image class="line-bg" :src="linSrc" mode="scaleToFill"></image>
				</view>
			</view>
			<view class="box bottom-view">
				<image class="lianjie" src="../../static/share/img-60-lianjie@2x.png" mode="aspectFit"></image>
				<view class="num-view">
					{{`${finishNum}/${itemList.length}`}}
				</view>
				<view class="chips-area">
					<view class="last" @click="cutList('last')" v-if="showItemlist.length > 0">
						<image v-if="nolast" class="btn-icon" src="../../static/game/btn-50-renwu-zuo-bukeyong@2x.png" mode="scaleToFill" />
						<image v-else class="btn-icon" src="../../static/game/btn-50-renwu-zuo@2x.png" mode="scaleToFill" />
					</view>
					<view class="chips-content">
						<view
							:class="{'chip-item': true ,'hasBkg':item}"
							v-for="(item) in showItemlist" :key="item.id"
						/>
						<view
							:class="{'chip-item': true ,'hasBkg':item}"
							v-if="showItemlist.length == 2 || showItemlist.length == 1"
						/>
						<view
							:class="{'chip-item': true ,'hasBkg':item}"
							v-if="showItemlist.length == 1"
						/>
					</view>
					<view class="next" @click="cutList('next')" v-if="showItemlist.length > 0">
						<image v-if="nonext" class="btn-icon" src="../../static/game/btn-50-renwu-you-bukeyong@2x.png" mode="scaleToFill" />
						<image v-else class="btn-icon" src="../../static/game/btn-50-renwu-you@2x.png" mode="scaleToFill" />
					</view>
				</view>
			</view>

			<movable-area class="movable-area-bg"
				id="img-bg">
				<movable-view
					v-for="(item,index) in itemList"
					v-if="item.isDisabled"
					:key="index"
					direction="all"
					disabled="false"
					scale="true"
					:x="item.position.x"
					:y="item.position.y"
					:scale-value="item.scale"
					:data-index = "index"
					:style="{width: item.size.width + 'px',height: item.size.height+ 'px'}"
				>
					<view>
						<image
							:style="{width: item.size.width + 'px',height: item.size.height+ 'px'}"
							:src="item.src" mode="aspectFit"
						></image>
					</view>
				</movable-view>
				<movable-view
					v-for="(item,index) in showItemlist"
					:key="index"
					direction="all"
					scale="true"
					:x="movingItem.id == item.id && !isMoveing ? touchStart.x  : item.startPosition.x"
					:y="item.startPosition.y || touchStart.y"
					:scale-value="item.scale"
					:data-item = "item"
					:data-index = "index"
					:disabled="item.isDisabled"
					:style="{width: item.size.width + 'px',height: item.size.height+ 'px'}"
					@touchstart="touchstart"
					@touchmove="touchmove"
					@touchend="touchend"
				>
					<view>
						<image
							:style="{width: item.size.width + 'px',height: item.size.height+ 'px'}"
							:src="item.src" mode="aspectFit"
						></image>
					</view>
				</movable-view>
			</movable-area>
		</view>

		<!--Excellent -->
		<view class="dailog_view" v-if="isShowExcellent">
			<view class="dailog_screen open-treasure-box">
				<image class="opne-bg-1" src="../../static/game/img-renwu-excellent-caidai@2x.png" mode="scaleToFill"></image>
				<image class="heart-bounces opne-bg-2" src="../../static/game/img-502-guang@2x.png" mode="aspectFit"></image>
				<image class="opne-bg-4" src="https://file-oss.putaocdn.com/minhangwenchuang/game/img-renwu-174-great@2x.png" mode="aspectFit"></image>
				<button class="cu-btn btn-get-key" v-on:click="onGameEndClick">
						<image src="../../static/game/btn-anniu-130-renwu-yaoshi@2x.png" mode="scaleToFill"></image>
						<view>
							<image src="../../static/game/icon-48-yaoshi@2x.png" mode="aspectFit"></image>
							<text>领取钥匙碎片</text>
						</view>
				</button>
			</view>
			<view class="background_screen" ></view>
		</view>

		<!--good || great-->
		<view class="dailog_view" v-if="isShowGood">
			<view class="dailog_screen open-treasure-box">
				<image class="opne-bg-1" src="../../static/game/img-renwu-excellent-caidai@2x.png" mode="scaleToFill"></image>
				<image class="heart-bounces opne-bg-2" src="../../static/game/img-502-guang@2x.png" mode="aspectFit"></image>
				<image v-if="isGood" class="opne-bg-5" src="https://file-oss.putaocdn.com/minhangwenchuang/game/img-renwu-146-good@2x.png" mode="aspectFit"></image>
				<image v-if="!isGood" class="opne-bg-5" src="https://file-oss.putaocdn.com/minhangwenchuang/game/img-renwu-146-great@2x.png" mode="aspectFit"></image>
			</view>
			<view class="background_screen" ></view>
		</view>

		<!--打开宝箱 -->
		<view class="dailog_view" v-if="isShowOpenBoxView" >
			<!-- <view class="dailog_view" v-if="true" > -->
			<view class="dailog_screen open-treasure-box" @click="onOpenBox">
				<image class="opne-bg-1" src="../../static/game/img-renwu-excellent-caidai@2x.png" mode="scaleToFill"></image>
				<image class="heart-bounces opne-bg-2" src="../../static/game/img-502-guang@2x.png" mode="aspectFit"></image>
				<image class="opne-bg-3" src="https://file-oss.putaocdn.com/minhangwenchuang/game/img-renwu-baoxiang-kaiqi@2x.png" mode="aspectFit"></image>
			</view>
			<view class="background_screen" ></view>
		</view>
		<!-- 打开宝箱 -->
		<view class="dailog_view" v-if="isShowOpened">
			<!-- <view class="dailog_view" v-if="true"> -->
			<view class="dailog_screen opened">
				<image class="opened-bg" src="../../static/game/img-renwu-tankuang-980-bg@2x.png" mode="scaleToFill"></image>
				<image class="opened-status-img" :src="prizeImg || openList[openStatus - 1].img" mode="aspectFit"></image>
				<!-- <view class="opened-status-status" ><text>{{openList[openStatus - 1].detail}}</text></view> -->
				<!-- <view class="opened-status-status" ><text>{{prizeDesc}}</text></view>
				<view>
					新增加的描述部分
					{{prizeDescription}}
				</view> -->

				<view :class="['opened-status-desc-area',openStatus == 3 ?'has-desc':'']">
					<view class="opened-status-status" ><text>{{prizeDesc}}</text></view>
					<view class="opened-status-desc" v-if="openStatus == 3">
						{{prizeDescription}}
					</view>
				</view>

				<button class="cu-btn btn-next" @click="onLingJiang">
					<image src="../../static/me/btn-anniu-130-zhengchang@2x.png" mode="aspectFit"></image>
					<text>{{openList[openStatus - 1].btnText}}</text>
				</button>
			</view>
			<view class="background_screen" ></view>
		</view>
		<!-- 继续闯关 -->
		<button v-if="isShowBtn" class="cu-btn btn-open" @click="onNextClick">
				<image src="../../static/me/btn-anniu-130-zhengchang@2x.png" mode="scaleToFill"></image>
				<text>继续闯关</text>
		</button>
	<!-- </movable-area> -->
	</view>
</template>

<script>
import mockData from './data'
import Dom from '../../utils/dom.js'
import {getUserTaskDo,getUserInfo,getUserBoxOpen,getUserBoxList,getUserFinsh,getPuzzleInfo} from '../../tool/userTool.js'
import {getNextPoint,playMp3,playMpBg,endMpBg,endMp3} from "../../tool/pubTool.js"
import {toast} from '../../utils/util.js'

export default {
	data() {
		return {
			innerBg:'',
			prizedata:'', // 获奖的作品
			gameInfo:null,
			boxList:null,
			datasorce:null,
			finishNum: 0, // 完成的进度
			bgReact:{"id":"img-bg","dataset":{},"left":20,"right":355,"top":137,"bottom":617,"width":335,"height":480},
			bgSrc:"../../static/game/img-renwu-jimuqiang.jpg",
			linSrc:'',
			positionScale: '',
			chipScale: '',
			touchStart: {
				x: 0,
				y: 0
			},
			prizeDesc: '',
			prizeImg: '', // 新增加的奖品图片
			prizeDescription: "", // 兑换的说明
			nolast: false,
			nonext: false,
			touchMoving: {
				x: 0,
				y: 0
			}, // 标识移动端距离
			offset: 15, // 偏移量
			isMoveing:false,
			movingItem: null,
			itemList: [],
			showItemlist: [], // 底部显示的列表
			usedList:[],
			isShowOpenBoxView:false, //打开宝箱弹窗
			isShowExcellent:false, //Excellent弹窗
			isShowGood:false, //good弹窗
			isGood:false ,  //显示good 还是 great

			//领奖
			isShowOpened:false,
			openStatus:4,
			openList: mockData.openList,
			boxId:null,

			nowGuideId:uni.getStorageSync("nowGuideId"), //选中导游ID
			guideRole:["../../static/share/img-xiangqing-196-bubu@2x.png",
			"../../static/share/img-xiangqing-196-lulu@2x.png",
			"../../static/share/img-xiangqing-196-keke@2x.png"],
			isShowBtn:false
		};
	},

	async onLoad(option) {
		let jsonStr = option.jsonStr;
		let data = JSON.parse(jsonStr);
		this.datasorce = data;
		// playMp3({type:"bg",loop:true,isNew:true})

		if(!this.datasorce.isShowKey){
			playMp3({type:5})
			setTimeout(() => {
				// playMpBg();
				this.playMpBgFun()
			}, 8000)
		}else {
			setTimeout(() => toast('请把积木墙补充完整吧'), 900)
			// playMpBg();
			this.playMpBgFun()
		}
		this.getUserInfo();
		const getHeightClick =async() => {
			return new Promise((r,e)=>{
				const query = uni.createSelectorQuery()
				query.select('#img-bg').boundingClientRect(data => {
				  r(data)
				}).exec();
			})
		};
		let react = await getHeightClick()
		this.bgReact = react;
		this.bgWidth = react.width;
		this.bgHeight = react.height;
		this.getPuzzleInfo(data.id) // 获取拼图

	},
	onShow() {
		// getPuzzleInfo()
		// this.itemList = mockData.sjlgz.chipsList
		// setTimeout(() => {
		// 	this.cutList('reset')
		// }, 500)
	},
	onHide(){
		// endMpBg();
		this.innerBg.destroy();
		endMp3();
	},
	onUnload(){
		// endMpBg();
		this.innerBg.destroy();
		endMp3();
	},
	methods: {
		playMpBgFun() {
			this.innerBg = uni.createInnerAudioContext();
			this.innerBg.autoplay = true;
			this.innerBg.src = "https://file-oss.putaocdn.com/minhangwenchuang/video/bg.mp3"
			this.innerBg.loop = true;
		},
		async getPuzzleInfo(id){
			let res = await getPuzzleInfo({id});
			if(res) {
				let lists = res.chipsList
				lists = this.shuffle(lists)
				this.itemList = lists
				this.linSrc= res.bkg
				this.positionScale= res.positionScale
				this.chipScale= res.chipScale
				setTimeout(() => {
					this.cutList('reset')
				}, 500)
			}
		},
		async getUserInfo(){
			let res = await getUserInfo();
			this.gameInfo = res;
		},
		async getEndAddressList(){
			await getUserFinsh();

		},
		touchstart(e) {
			playMp3({type:"xz",isNew:true})
			const item = e.mp.currentTarget.dataset.item;
			const touchs = e.mp.touches[0];
			this.touchStart = {
				x: touchs.pageX,
				y:touchs.pageY
			}
			this.isMoveing = true
			this.movingItem = item
		},
		touchmove(e){
			const touchs = e.mp.touches[0];
			this.touchMoving = {
				x: touchs.pageX,
				y:touchs.pageY
			}

		},
		touchend(e){
			let moves = {
				x: this.touchMoving.x - this.touchStart.x,
				y: this.touchMoving.y - this.touchStart.y
			}// 移动的 x y
			const item = e.mp.currentTarget.dataset.item;
			let checkResult = this.checkPosition(item, moves)
			if(checkResult){
				playMp3({type:"cg",isNew:true})
				this.itemList.map((itemold, index) => {
					if(itemold.id == item.id){
						itemold.isDisabled = true
						this.isMoveing = false
						this.movingItem = null
						this.finishNum = this.finishNum + 1
						this.checkLength()
						this.cutList('reset')
						return
					}else{
						this.isMoveing = false
						this.movingItem = null
					}
				})
			}else{
				this.isMoveing = false
				this.movingItem = null
			}

		},
		async onOpenBox(){
			this.isShowOpenBoxView = false
			await this.openBoxPost()

		},

		async getBoxList(){
			let res = await getUserBoxList();
			this.boxList = res;
		},
		async openBoxPost(){
			let res = await getUserBoxOpen({
				params:{
					"box_no":Math.ceil(this.gameInfo.key_num / 10)
				}
			});
			this.isShowOpened = true;
			if(res.status === 1){
				this.openStatus = 1;
				this.prizeDesc= '很遗憾，本次宝箱内未抽中奖品，你还有机会从下一个宝箱内获得，快点完成任务开启下一个宝箱吧'
				this.prizeDescription = res.description // 备注部分
				this.prizeImg = res.img_url
			}
			if(res.status === 2 || res.status === 3||res.status === 4){
				this.prizedata = res
				if(res.prize_type === 2){
					this.openStatus = 2;
					this.prizeDesc= `恭喜你获得“${res.prize_name}”门票一张，可前往相关兑换服务网点凭借手机号码进行兑换，门票有限期1年。`
					this.prizeDescription = res.description // 备注部分
					this.prizeImg = res.img_url
				}
				if(res.prize_type === 1){
					this.openStatus = 3;
					this.boxId = res.user_treasure_box_id;
					this.prizeDesc= `恭喜你，获得${res.prize_name}一套，快去填写收货信息吧。`
					this.prizeDescription = res.description // 备注部分
					this.prizeImg = res.img_url
				}
			}
		},
		onLingJiang(){
			this.isShowOpened = false;

			if(this.openStatus === 1){
				this.onNextClick();
			}else if (this.openStatus === 2){
				uni.navigateTo({
					url:"/pages/addressList/addressList"
				})
			}else if (this.openStatus === 3){
				console.log(this.prizedata)
				console.log(JSON.stringify(this.prizedata))
				console.log('传递的数据')
				uni.navigateTo({
					url:`/pages/receiveAward/receiveAward?boxId=${this.boxId}&itemStr=${JSON.stringify(this.prizedata)}`
				})
			}
		},
		// 游戏结束
		async onGameEndClick(){
			let res = await getUserTaskDo({params:{
				"scenic_id":this.datasorce.id
			}});
			console.log(res);
			this.isShowExcellent = false

			await this.getEndAddressList();
			 await this.getUserInfo();
			//
			let ketNum = this.gameInfo.key_num;
			if(ketNum % 10 === 0){
				// toast(`恭喜你集齐${ketNum}枚钥匙碎片即刻开启宝箱吧`);
				playMp3({type:9})
				this.isShowOpenBoxView = true
			}else{
				toast("恭喜你成功拼成了积木墙,继续闯关吧")
				this.isShowBtn = true;
			}
		},
		checkLength(){ // 建测拼图进度
			setTimeout(()=>{
				if(this.finishNum === 1){
					if(this.datasorce.isShowKey){
						// toast("WOW,恭喜你离成功更进一步啦！")
					}else{
						playMp3({type:6})
						// this.isShowGood =true;
						// this.isGood = false;
						// setTimeout(()=>{
						// 	this.isGood = false;
						// 	this.isShowGood =false;
						// },2000)
					}
				}else if(this.finishNum ===Math.ceil(this.itemList.length / 2)){
					if(this.datasorce.isShowKey){
						toast("WOW,恭喜你离成功更进一步啦！")
					}else{
						playMp3({type:7})
						this.isShowGood =true;
						this.isGood = false;
						setTimeout(()=>{
							this.isGood = false;
							this.isShowGood =false;
						},2000)
					}
				}else if(this.finishNum == this.itemList.length){
					if(this.datasorce.isShowKey){
						toast("恭喜你成功拼成了积木墙")
						this.isShowBtn = true;
					}else{
						playMp3({type:8})
						this.isShowExcellent = true
					}
				}
			},300)
		},
		onNextClick(){
			// let nextList = getNextPoint();
			// if(nextList.length > 0){
			// 	uni.redirectTo({
			// 		url:`/pages/attractionDetail/attractionDetail?id=${nextList[0]}`
			// 	})
			// }
			uni.reLaunch({
				url:`/pages/index/index`
			})
		},
		checkPosition(item, moves){
			let {startPosition, position} = item
			if(
				(position.x - this.offset) < (startPosition.x + moves.x) && (startPosition.x + moves.x) < (position.x + this.offset) &&
				(position.y - this.offset) < (startPosition.y + moves.y) && (startPosition.y + moves.y) < (position.y + this.offset)
			){
				return true
			}else {
				return false
			}
		},

		shuffle(arr) { // 随机打乱数组
		　　for (var i = arr.length - 1; i >= 0; i--) {
		　　　　var randomIndex = Math.floor(Math.random() * (i + 1));
		　　　　var itemAtIndex = arr[randomIndex];
		　　　　arr[randomIndex] = arr[i];
		　　　　arr[i] = itemAtIndex;
		　　}
		　　return arr
		},
		cutList(type){
			let list = this.setPosition()
			let cutedList = []
			list.map((item) => {
				if(!item.isDisabled) cutedList.push(item)
			})
			if(type == 'reset'){
				this.numStart = 0
				cutedList = cutedList.slice(0, 3)
			}else if(type == 'next'){
				if(this.numStart + 3 < cutedList.length){
					this.nolast = false
					this.numStart =  this.numStart +1
					cutedList = cutedList.slice(this.numStart, this.numStart + 3)
				}else {
					this.nonext = true
					cutedList = cutedList.slice(this.numStart, this.numStart + 3)
				}
			}else if(type == 'last'){
				if(this.numStart >= 1){
					this.nonext = false
					this.numStart =  this.numStart - 1
					cutedList = cutedList.slice(this.numStart, this.numStart + 3)
				}else {
					this.nolast = true
					cutedList = cutedList.slice(this.numStart, this.numStart + 3)
				}
			}

			cutedList.map((chip, index) => {
				chip.startPosition = this.getStartPosition(chip, index)
			})
			this.showItemlist = cutedList
		},
		setPosition(){
			let list = this.itemList
			list.map((chip, index) => {
				chip.position = this.getPosition(chip)
				chip.size = this.getWidth()
				chip.startPosition = this.getStartPosition(chip)
			})
			return list
		},
		getWidth(){
			return {
				width: this.bgWidth / this.positionScale * 3,
				height: this.bgWidth / this.positionScale * 3,
			}
		},
		getPosition(chip, index){
			return {
				x: this.bgWidth / this.positionScale * chip.column,
				y: this.bgWidth / this.positionScale * chip.row
			}
		},
		getStartPosition(chip, index){
			let itemWidth = this.bgWidth / 5
			let left
			if(index== 0){
				left = 0.5 * itemWidth
			}else if(index== 1){
				left = 2 * itemWidth
			}else if(index == 2){
				left = 3.5 * itemWidth
			}
			return {
				x: left,
				y: this.bgHeight - this.bgWidth / this.positionScale * 3.5
			}
		}
	}
};
</script>

<style lang="scss">
	@import './style.scss';
</style>
